#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/9/30 15:07
@Author:  ThinHeader
@File: wechat_tools.py
@Software: PyCharm
"""
import json
import time
from urllib.parse import urlunparse, quote, parse_qsl, urlparse

from account.models import User
from common.decorators import Helper
from common.tools.redis_tool import RedisStat
from common.wx.config import WxPayConf_shop
from common.wx.lib import WeixinHelper
from open.models import WxPublicMapShop, WxPublicAccess
from shop.models import ShopInfo


def getsign(request, shop_id, long2short=False):
    """获得微信的签名"""
    url = request.build_absolute_uri()
    token = ''
    try:
        shop = ShopInfo.objects.get(id=shop_id, status=ShopInfo.STATUS_VALID)
    except ShopInfo.DoesNotExist:
        return None
    if shop.user.pay_type in [User.SELF_PUB, User.PAY_WX_SERVICE, ]:
        try:
            pms = WxPublicMapShop.objects.get(shop_id=shop_id, status=WxPublicMapShop.STATUS_VALID)
            pa = WxPublicAccess.objects.get(app_id=pms.app_id, status=WxPublicAccess.STATUS_VALID)
            ticket = pa.ticket
            token = pa.access_token
        except WxPublicMapShop.DoesNotExist:
            return None
        except WxPublicAccess.DoesNotExist:
            return None

        sign = Helper.jsapi_sign_ticket(ticket, url)
        sign['appId'] = pms.app_id

    elif shop.user.pay_type in [User.PAY_XIAODU]:
        try:
            pa = WxPublicAccess.objects.get(app_id='wx87433e29e621c32e', status=WxPublicAccess.STATUS_VALID)
            ticket = pa.ticket
            token = pa.access_token
        except WxPublicAccess.DoesNotExist:
            return None
        sign = Helper.jsapi_sign_ticket(ticket, url)
        sign['appId'] = 'wx87433e29e621c32e'
    else:
        return None

    parse = urlparse(url)
    query = parse.query.replace('amp;', '')
    params_dict = dict(parse_qsl(query))
    # query = '&'.join([key+'='+value for key, value in params_dict.items()])

    # state_get = params_dict.get('state')
    # logger.debug('state_get=%s' % state_get)

    # state_list = state_get.split('|') if state_get else []  # aa|bb|cc  aa:最近一级上级推客 bb:谁转发过来 cc:时间戳
    # if len(state_list) != 3:
    #     try:
    #         sm = SalesMan.objects.filter(shop_id=shop_id, user=request.user, status=SalesMan.STATUS_VALID).first()
    #         state = '%s|%s|%d' % (request.user.id, request.user.id, int(time.time()))
    #     except SalesMan.DoesNotExist:
    #         state = '0|%s|%d' % (request.user.id, int(time.time()))
    # else:
    #     # 判断自己是不是推客
    #     try:
    #         sm = SalesMan.objects.filter(shop_id=shop_id, user=request.user, status=SalesMan.STATUS_VALID).first()
    #         state = '%s|%s|%d' % (request.user.id, request.user.id, int(time.time()))
    #         # logger.debug('state=%s' % state)
    #     except SalesMan.DoesNotExist:
    #         # 获取谁转发来的，判断此人是不是推客
    #         try:
    #             sm = SalesMan.objects.filter(shop_id=shop_id, user_id=state_list[1], status=SalesMan.STATUS_VALID).first()
    #             state = '%s|%s|%d' % (sm.user.id, request.user.id, int(time.time()))
    #         except SalesMan.DoesNotExist:
    #             # 判断推客身份是否有效
    #             try:
    #                 sm = SalesMan.objects.filter(shop_id=shop_id, user_id=state_list[0], status=SalesMan.STATUS_VALID).first()
    #                 state = '%s|%s|%d' % (sm.user.id, request.user.id, int(time.time()))
    #             except SalesMan.DoesNotExist:
    # 都不是推客
    state = '0|%s|%d' % (request.user.id, int(time.time()))

    # logger.debug('state=%s' % state)
    params_dict['state'] = quote(state)
    query = '&'.join([key+'='+value for key, value in params_dict.items()])
    # logger.debug('query=%s' % query)
    # return urlparse.urlunparse((parse.scheme, parse.netloc, parse.path, parse.params, query, parse.fragment))
    share_url = urlunparse((parse.scheme, parse.netloc, parse.path, parse.params, query, parse.fragment))
    sign['share_url'] = share_url

    if long2short:
        result = json.loads(WeixinHelper.long2short(share_url, token))
        if int(result['errcode']) == 0:
            sign['short_url'] = result['short_url']
    return sign
